package com.atguigu.gmall.payment.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private AlipayClient alipayClient;

    @Override
    public String submit(Long orderId) {
        //添加支付信息表
        PaymentInfo paymentInfo = paymentInfoService.insert(orderId, PaymentType.ALIPAY);
        //创建支付宝请求连接
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        Map map = new HashMap();
        //组装参数
        map.put("out_trade_no",paymentInfo.getOutTradeNo());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",paymentInfo.getTotalAmount());
        map.put("subject",paymentInfo.getSubject());
        request.setBizContent(JSONObject.toJSONString(map));

        //设置同步地址
        request.setReturnUrl(AlipayConfig.return_payment_url);
        //设置异步地址
        request.setNotifyUrl(AlipayConfig.notify_payment_url);

        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }
}
